package demo3;

//最小的k个数
public class TopK {
    public void topK(int[] array, int k) {
        int[] smallK = new int[k];
        for (int i = 0; i < k; i++) {
            smallK[i] = array[i];
        }
        createHeap(smallK);
        for (int i = k; i < array.length; i++) {
            if (array[i] < smallK[0]) {
                smallK[0] = array[i];
                shiftDown(smallK,0,k - 1);
            }
        }
        for (int i = 0; i < k; i++) {
            System.out.print(smallK[i] + " ");
        }
    }
    //建立大根堆
    public void createHeap(int[] array) {
        for (int parent = (array.length - 1 - 1) / 2; parent >= 0; parent--) {
            shiftDown(array,parent,array.length - 1);
        }
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int[] array,int root,int len) {
        int child = root * 2 + 1;
        while (child <= len) {
            if ((child + 1 <= len) && (array[child + 1] > array[child])) {
                child++;
            }
            if (array[root] < array[child]) {
                swap(array,root,child);
                root = child;
                child = root * 2 + 1;
            } else {
                break;
            }
        }
    }



    //交换
    public void swap(int[] array, int x, int y) {
        int temp = array[x];
        array[x] = array[y];
        array[y] = temp;
    }
}
